%%%-------------------------------------------------------------------
%%% @author Rain
%%% @copyright (C) 2022, <COMPANY>
%%% @doc
%%% @end
%%%-------------------------------------------------------------------
-module(gate_route_svr).

-behaviour(gen_server).

-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
    code_change/3]).

-record(state, {}).

%%%===================================================================
%%% Spawning and gen_server implementation
%%%===================================================================

start_link(Sock) ->
    gen_server:start_link(?MODULE, [Sock], []).

init([Sock]) ->
    gate_util:set_process_sock(Sock),
    {ok, #state{}}.

handle_call(_Request, _From, State = #state{}) ->
    {reply, ok, State}.

handle_cast(_Request, State = #state{}) ->
    {noreply, State}.

handle_info({from_client_msg, [MsgId, Content|_]}, State = #state{}) ->
    io:format("~p [RECV_MSG] USER(~p) MsgId ~p Content ~p ~n",[self(), get(uid_value), MsgId, Content]),
    gate_router:route(MsgId, Content),
    {noreply, State};

handle_info({to_client_msg, MsgId, Msg}, State = #state{}) ->
    gate_util:send_sock_msg(MsgId, Msg),
    {noreply, State};

handle_info({sock_lost, Reason}, State = #state{}) ->
    io:format("~p [SOCK_LOST] USER(~p) Reason ~p ~n",[self(), get(uid_value), Reason]),
    sock_lost(),
    {noreply, State};

handle_info(_Info, State = #state{}) ->
    {noreply, State}.

terminate(_Reason, _State = #state{}) ->
    ok.

code_change(_OldVsn, State = #state{}, _Extra) ->
    {ok, State}.

%%%===================================================================
%%% Internal functions
%%%===================================================================

sock_lost() ->
    case get(uid_value) of
        UidValue when is_integer(UidValue) ->
            obj_svr:stop_obj_svr(UidValue);
        _ ->
            pass
    end,
    exit(shutdown).

